import sys
import os
from .client import DatabaseClient
import getpass


class DatabaseCLI:
    """数据库命令行界面"""
    
    def __init__(self):
        self.client = DatabaseClient()
        self.running = False
    
    def start(self):
        """启动CLI"""
        print("="*60)
        print("           RBDB 数据库客户端")
        print("="*60)
        print("输入 'help' 查看帮助信息")
        print("输入 'quit' 或 'exit' 退出程序")
        print()
        
        # 连接到服务器
        if not self.client.connect():
            print("无法连接到数据库服务器，程序退出")
            return
        
        # 登录
        if not self._login():
            print("登录失败，程序退出")
            self.client.disconnect()
            return
        
        self.running = True
        
        # 主循环
        try:
            while self.running:
                self._main_loop()
        except KeyboardInterrupt:
            print("\n收到中断信号，正在退出...")
        finally:
            self.client.logout()
            self.client.disconnect()
    
    def _login(self) -> bool:
        """登录流程"""
        print("\n请登录到数据库:")
        print("默认用户: admin/admin123 (管理员), user/user123 (普通用户)")
        
        max_attempts = 3
        for attempt in range(max_attempts):
            try:
                username = input("用户名: ").strip()
                if not username:
                    continue
                
                password = getpass.getpass("密码: ")
                
                if self.client.login(username, password):
                    return True
                else:
                    remaining = max_attempts - attempt - 1
                    if remaining > 0:
                        print(f"登录失败，还有 {remaining} 次尝试机会")
                    else:
                        print("登录失败次数过多")
            
            except (EOFError, KeyboardInterrupt):
                print("\n登录被取消")
                return False
        
        return False
    
    def _main_loop(self):
        """主循环"""
        try:
            # 显示提示符
            if self.client.user_info:
                username = self.client.user_info['username']
                prompt = f"RBDB [{username}]> "
            else:
                prompt = "RBDB> "
            
            # 检查连接状态
            if not self.client.connected:
                print("\n连接已断开，正在退出...")
                self.running = False
                return
            
            command = input(prompt).strip()
            
            if not command:
                return
            
            # 处理特殊命令
            if command.lower() in ['quit', 'exit', 'q']:
                self.running = False
                return
            
            elif command.lower() == 'help':
                self._show_help()
                return
            
            elif command.lower() == 'clear':
                os.system('cls' if os.name == 'nt' else 'clear')
                return
            
            elif command.lower() == 'status':
                self._show_status()
                return
            
            elif command.lower().startswith('\\'):
                self._handle_meta_command(command)
                return
            
            # 执行SQL命令
            if command.endswith(';'):
                command = command[:-1]  # 移除分号
            
            # 添加超时检查
            try:
                result = self.client.execute_sql(command)
                if result is None:
                    print("SQL执行失败，请检查连接状态")
            except Exception as sql_error:
                print(f"SQL执行出错: {sql_error}")
        
        except (EOFError, KeyboardInterrupt):
            print("\n正在退出...")
            self.running = False
        except Exception as e:
            print(f"命令执行出错: {e}")
            print("如果问题持续，请重启客户端")
    
    def _show_help(self):
        """显示帮助信息"""
        print("\n可用命令:")
        print("  help          - 显示此帮助信息")
        print("  clear         - 清屏")
        print("  status        - 显示连接状态")
        print("  quit/exit/q   - 退出程序")
        print("\n元命令:")
        print("  \\d           - 显示所有表")
        print("  \\dt          - 显示表列表")
        print("  \\q           - 退出程序")
        print("\nSQL示例:")
        print("  SELECT * FROM users")
        print("  SELECT * FROM products")
        print("  SHOW TABLES")
        print("  INSERT INTO users VALUES (4, '赵六', 35, 'zhaoliu@example.com')")
        print("  UPDATE users SET age = 26 WHERE id = 1")
        print("  DELETE FROM users WHERE id = 1")
        print("\n注意: SQL语句可以不加分号")
    
    def _show_status(self):
        """显示状态信息"""
        print("\n连接状态:")
        print(f"  服务器: {self.client.host}:{self.client.port}")
        print(f"  连接状态: {'已连接' if self.client.connected else '未连接'}")
        if self.client.user_info:
            print(f"  当前用户: {self.client.user_info['username']}")
            print(f"  用户权限: {', '.join(self.client.user_info['permissions'])}")
            print(f"  登录时间: {self.client.user_info.get('session_created', 'N/A')}")
    
    def _handle_meta_command(self, command: str):
        """处理元命令"""
        cmd = command.lower().strip()
        
        if cmd in ['\\d', '\\dt']:
            self.client.execute_sql("SHOW TABLES")
        elif cmd == '\\q':
            self.running = False
        else:
            print(f"未知的元命令: {command}")
            print("输入 'help' 查看可用命令")

def main():
    """客户端主函数"""
    cli = DatabaseCLI()
    cli.start()

if __name__ == "__main__":
    main()